package com.example.controller;


import com.example.entity.Goods;
import com.example.entity.User;
import com.example.service.GoodsService;
import com.example.service.UserService;
import org.apache.ibatis.ognl.ASTTest;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @RequestMapping("/list")
    public  String list(Model model,@RequestParam(required = false)String username){
//       List<User> userList = userService.getAllUser();
//       model.addAttribute("userList",userList);

        List<User> userList = new ArrayList<>();
        if (username != null&&! username.trim().isEmpty()){
            userList = userService.searchByUsername(username);
        }else {
            userList = userService.getAllUser();
        }
        model.addAttribute("userList",userList);
        model.addAttribute("searchUsername",username);//searchUsername：存储当前搜索的关键词 用于在视图中回显搜索框中的内容
        System.out.println(userList);
       return "admins/list";
    }
    @GetMapping("/add")
    public String toAddPage() {
        return "admins/add";
    }

    @PostMapping("/add")
    public String add(User user) {
        userService.addUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/edit/{uid}")
    public String toEditPage(@PathVariable("uid") Integer uid, Model model) {
        User user = userService.getUserById(uid);
        model.addAttribute("user", user);
        return "admins/edit";
    }

    @PostMapping("/edit")
    public String edit(User user) {
        userService.updateUser(user);
        return "redirect:/user/list";
    }

    @GetMapping("/delete/{uid}")
    public String delete(@PathVariable("uid") Integer uid) {
        userService.deleteUser(uid);
        return "redirect:/user/list";
    }
    @PostMapping("/login")
    public ModelAndView login(@RequestParam String username,
                              @RequestParam String password,
                              @RequestParam String code,
                              HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        HttpSession session = request.getSession();

        // 1. 验证码校验（不区分大小写）
        String sessionCode = (String) session.getAttribute("verifycode");
        if (sessionCode == null || !sessionCode.equalsIgnoreCase(code.trim())) {
            mv.addObject("error", "验证码错误或已过期");
            mv.setViewName("user/login");
            return mv;
        }
        // 2. 验证用户名密码
        User user = this.userService.findByNameAndPassword(username, password);
        if (user == null) {
            mv.addObject("error", "用户名或密码错误");
            mv.setViewName("user/login");
            return mv;
        }

        // 3. 登录成功处理
        session.setAttribute("user", user);

        switch (user.getRole()) {
            case 0: // 管理员
                mv.setViewName("admin");
                break;
            case 1: // 学生
                int page = 1;
                int pageNum = 6;
                List<Goods> goods = this.goodsService.findGoodsByPage(page, pageNum);
                int totalPage = this.goodsService.totalPage(pageNum);

                mv.addObject("goods", goods);
                mv.addObject("currentPage", page);
                mv.addObject("totalPage", totalPage);
                mv.setViewName("student/home");
                break;
            case 2: // 教师
                mv.addObject("name", user.getName());
                mv.setViewName("redirect:/teacher/list");
                break;
            default:
                mv.setViewName("redirect:/");
        }

        return mv;
    }
    @GetMapping("/register")
    public String toRegisterPage() {
        return "user/register"; // 返回注册页面
    }

    @PostMapping("/register")
    public String register(User user, Model model) {
        // 保存用户
        if (userService.addUser(user)) {
            return "user/login"; // 注册成功跳转到登录页
        } else {
            model.addAttribute("error", "注册失败，请稍后重试");
            return "user/register";
        }
    }


    //修改个人信息

    @GetMapping("/update1")
    public ModelAndView findByUid(Integer uid) {
        ModelAndView mv = new ModelAndView();
        User user = userService.getUserById(uid);
        System.out.println(user);
        mv.addObject("uid", user.getUid());
        mv.addObject("user", user);
        mv.setViewName("teacher/update");
        return mv;
    }
    @GetMapping("/getVerify")
    public void getVerify(HttpServletRequest request,
                          HttpServletResponse response) {
        try {
            // 强制浏览器不缓存
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");

            new com.example.util.RandomValidateCode().getRandcode(request, response);
        } catch (Exception e) {
//            logger.error("验证码生成异常", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
